package com.hdu.controller;


import com.hdu.req.TaskCreateReq;
import com.hdu.req.TaskDeleteReq;
import com.hdu.result.R;
import com.hdu.service.TaskService;
import lombok.extern.slf4j.Slf4j;
import lombok.val;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;


import static java.util.Objects.isNull;
import static org.apache.commons.lang3.StringUtils.isEmpty;
import static com.hdu.util.ParamChecker.unValidParam;

@Slf4j
@RestController
@RequestMapping("task")
public class TaskController {


    private final TaskService taskService;

    public TaskController(TaskService taskService) {
        this.taskService = taskService;
    }

    @PostMapping("add")
    public R addTask(@RequestBody TaskCreateReq req) {
        log.info("TaskController.addTask(), req : {}", req);
        unValidParam(
                isEmpty(req.getTaskName())
                        || req.getPriority() < 0
                        || isNull(req.getTaskParam())
                        || req.getExecuteTime() <= System.currentTimeMillis(),
                "参数不合法"
        );
        val result = taskService.addTask(
                req.getTaskName(),
                req.getPriority(),
                req.getTaskParam(),
                req.getExecuteTime()
        );
        return result ? R.success() : R.fail("添加任务失败");
    }


    @PostMapping("delete")
    public R deleteTask(@RequestBody TaskDeleteReq req) {
        log.info("TaskController.deleteTask(), req : {}", req);
        boolean result = taskService.deleteTask(req.getId());
        return result ? R.success() : R.fail("删除任务失败");
    }

}
